package com.management.vtribe.controller;

import com.management.vtribe.Bean.Manager;
import com.management.vtribe.config.Result;
import com.management.vtribe.config.VerifyCode;
import com.management.vtribe.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class ManagerController {
    @Autowired
    ManagerService managerService;

    @RequestMapping("/verifyManager")
    public Result verifyManager(HttpServletRequest request, String verifyCode, String username, String password){
        String text = (String)request.getSession().getAttribute("verify_code");//获取session里的验证码
        if (verifyCode==null||!verifyCode.toLowerCase().equals(text.toLowerCase())){//与前端传来的验证码比对
            return new Result(400,"验证码错误！");
        }else {
            Manager manager = managerService.verifyManager(username,password);
            if(manager==null){
                return new Result(401,"用户名或密码错误！");
            }else{
                return new Result(200,username);
            }
        }
    }

    @RequestMapping("/getManager")
    public Manager getManager(String username){
        return managerService.getManagerByUsername(username);
    }

    @RequestMapping("/verifyCode")
    public void verifyCode(HttpSession session, HttpServletResponse response) throws IOException {
        VerifyCode verifyCode = new VerifyCode();//调用生成验证码工具类
        BufferedImage image = verifyCode.getImage();//获得验证码图片到流中
        String text = verifyCode.getText();//获取验证码文本
        session.setAttribute("verify_code",text);//把文本存入session中，用于与前端返回进行比较
        verifyCode.output(image,response.getOutputStream());//把图片返回前端

    }
}
